package org.szrcb.temu.SalesManage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szrcb.temu.SalesManage.Vo.ResultVO;
import org.szrcb.temu.SalesManage.po.*;
import org.szrcb.temu.SalesManage.pojo.MallInfo;
import org.szrcb.temu.SalesManage.pojo.UserInfo;
import org.szrcb.temu.SalesManage.pojo.Warehouse;
import org.szrcb.temu.SalesManage.req.SkuSalesReq;
import org.szrcb.temu.SalesManage.req.WarehouserReq;
import org.szrcb.temu.SalesManage.service.MallInfoService;
import org.szrcb.temu.SalesManage.service.UserInfoService;
import org.szrcb.temu.SalesManage.service.WarehouseService;
import org.szrcb.temu.SalesManage.utils.ResultVOUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class WarehouseController {

    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private MallInfoService mallInfoService;


    private JSONObject getWarehouseJson(String httpUrl, String cookie, String mallId, WarehouserReq req) {
        StringBuilder content = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Origin", "https://seller.kuajingmaihuo.com");
            conn.setRequestProperty("cookie", cookie);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("MallId", mallId);
            conn.setDoOutput(true);

            String warehouseReqJson = JSON.toJSONString(req);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(warehouseReqJson.getBytes());
            }

            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                content.append(inputLine);
            }
            br.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return JSONObject.parseObject(content.toString());
    }

    private WarehouseResult getWarehouseResult(String cookie, String mallId, WarehouserReq warehouserReq) {
        JSONObject warehouseJson = null;
        boolean warehouseBoolean = false;
        //循环请求数据
        while (!warehouseBoolean) {
            warehouseJson = getWarehouseJson("https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/venom/sales/management/listWarehouse", cookie, mallId, warehouserReq);
            String errorCode = warehouseJson.getObject("errorCode", String.class);
            if ("40001".equals(errorCode)) {
                throw new RuntimeException("登录过期，请重新登录");
            }
            if ("1000000".equals(errorCode)) {
                warehouseBoolean = warehouseJson.getObject("success", boolean.class);
            }
        }
        return warehouseJson.getObject("result", WarehouseResult.class);
    }


    @PostMapping("/updateBuyPrice")
    public ResultVO updateBuyPrice(@RequestHeader("access_token") String token, @RequestParam(value = "skuExtCode") String skuExtCode, @RequestParam(value = "buyingPrice") String buyingPrice) {
        try {
            String cookie = "";
            if (token != null && !"".equals(token.trim())) {
                cookie = userInfoService.queryUserCookie(token);
                if ("".equals(cookie.trim())) {
                    return ResultVOUtil.error(1, "token不正确,请先登录Temu后台");
                }
            }
            warehouseService.updateBuyingPriceBySkuExtCode(skuExtCode, buyingPrice);
        } catch (Exception e) {

        }
        return ResultVOUtil.success("success");

    }


    @PostMapping("/syncWarehouse")
    public ResultVO syncWarehouse(@RequestHeader("access_token") String token, @RequestParam(value = "mallId") String mallId) {
        try {
            String cookie = "";
            if (token != null && !"".equals(token.trim())) {
                cookie = userInfoService.queryUserCookie(token);
                if ("".equals(cookie.trim())) {
                    return ResultVOUtil.error(1, "token不正确,请先登录Temu后台");
                }
            }
            //先同步数据
            int pageNo = 1;
            int pageSize = 40;
            WarehouserReq warehouserReq = new WarehouserReq();
            warehouserReq.setPageNo(pageNo);
            warehouserReq.setPageSize(pageSize);
            warehouserReq.setIsLack(0);
            warehouserReq.setPriceAdjustRecentDays(7);

            WarehouseResult warehouseResult = getWarehouseResult(cookie, mallId, warehouserReq);
            List<subOrder> page1ResultList = warehouseResult.getSubOrderList();

            if (page1ResultList != null && page1ResultList.size() > 0) {
                updateWarehouse(page1ResultList);
            }
            Integer total = warehouseResult.getTotal();

            //计算页数，查询
            int totalPages = (int) Math.ceil((double) total / pageSize); // 总页数，使用Math.ceil向上取整
            if (totalPages > 1) {
                for (int i = pageNo + 1; i <= totalPages; i++) {
                    warehouserReq.setPageNo(i);
                    warehouseResult = getWarehouseResult(cookie, mallId, warehouserReq);
                    List<subOrder> subOrderList = warehouseResult.getSubOrderList();

                    if (subOrderList != null && subOrderList.size() > 0) {
                        updateWarehouse(subOrderList);
                    }
                }
            }

            return ResultVOUtil.success("sucess");
        } catch (Exception e) {
            return ResultVOUtil.error(1, e.getMessage());
        }
    }

    private List<Warehouse> setWarehouseList(List<Warehouse> warehouseList, Map<Long, Integer> skuSalesMap) {
        warehouseList.forEach(warehouse -> {
            //昨日销量
            Integer setYesterDaySaleVolume = skuSalesMap.get(Long.valueOf(warehouse.getProductSkuId() == null ? "0" : warehouse.getProductSkuId()));
            warehouse.setYesterDaySaleVolume(setYesterDaySaleVolume == null ? 0 : setYesterDaySaleVolume);

            //销售额
            warehouse.setYesterDaySalePrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getYesterDaySaleVolume()) * warehouse.getSupplierPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));
            warehouse.setTodaySalePrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getTodaySaleVolume()) * warehouse.getSupplierPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));//今日销售额=今日销售数量*申报价格
            warehouse.setLastSevenDaysSalePrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastSevenDaysSaleVolume()) * warehouse.getSupplierPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));//7日销售额=7日销售数量*申报价格
            warehouse.setLastThirtyDaysSalePrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastThirtyDaysSaleVolume()) * warehouse.getSupplierPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));//30日销售额=30日销售数量*申报价格


            Double profit = warehouse.getSupplierPrice() - warehouse.getBuyingPrice();
            warehouse.setProfit(profit);
            //利润
            warehouse.setYesterDaySaleProfit(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getYesterDaySaleVolume()) * profit).setScale(2, RoundingMode.HALF_UP).doubleValue()));
            warehouse.setTodaySaleProfit(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getTodaySaleVolume()) * profit).setScale(2, RoundingMode.HALF_UP).doubleValue()));//今日利润=今日销售额*单件利润
            warehouse.setLastSevenDaysSaleProfit(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastSevenDaysSaleVolume()) * profit).setScale(2, RoundingMode.HALF_UP).doubleValue()));//7日利润=7日销售额*单件利润
            warehouse.setLastThirtyDaysSaleProfit(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastThirtyDaysSaleVolume()) * profit).setScale(2, RoundingMode.HALF_UP).doubleValue())); //30日利润=30日销售额*单件利润


//            new BigDecimal(Double.valueOf(warehouse.getLastThirtyDaysSaleVolume()) * warehouse.getBuyingPrice()).setScale(2,RoundingMode.HALF_UP).doubleValue())
            //本金
            warehouse.setYesterDaySaleBuyingPrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getYesterDaySaleVolume()) * warehouse.getBuyingPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));
            warehouse.setTodaySaleBuyingPrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getTodaySaleVolume()) * warehouse.getBuyingPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));//今日销售额=今日销售数量*本金
            warehouse.setLastSevenDaysSaleBuyingPrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastSevenDaysSaleVolume()) * warehouse.getBuyingPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));
            warehouse.setLastThirtyDaysSaleBuyingPrice(Double.valueOf(new BigDecimal(Double.valueOf(warehouse.getLastThirtyDaysSaleVolume()) * warehouse.getBuyingPrice()).setScale(2, RoundingMode.HALF_UP).doubleValue()));

            warehouse.setHuoZhi(warehouse.getWarehouseInventoryNum() * warehouse.getBuyingPrice());

            if (warehouse.getSupplierPrice() > 0.00) {
                BigDecimal bd = new BigDecimal(profit / warehouse.getSupplierPrice() * 100);
                bd = bd.setScale(2, RoundingMode.HALF_UP);
                warehouse.setTotalProfit(bd.toString() + "%");
            } else {
                warehouse.setTotalProfit("100%");
            }
        });
        return warehouseList;
    }

    private Map<Long, Integer> querySkuSalesNumber(String cookie, SkuSalesReq req, String mallId) {
        JSONObject skuSalesJson = null;
        boolean skuSalesBoolean = false;
        //循环请求数据
        while (!skuSalesBoolean) {
            skuSalesJson = getSkuSalesJson("https://seller.kuajingmaihuo.com/oms/bg/venom/api/supplier/sales/management/querySkuSalesNumber", cookie, mallId, req);
            String errorCode = skuSalesJson.getObject("errorCode", String.class);
            if ("40001".equals(errorCode)) {
                throw new RuntimeException("登录过期，请重新登录");
            }
            if ("1000000".equals(errorCode)) {
                skuSalesBoolean = skuSalesJson.getObject("success", boolean.class);
            }
        }

        List<SkuSales> skuSalesList = JSON.parseArray(skuSalesJson.getString("result"), SkuSales.class);
        HashMap<Long, Integer> map = new HashMap<>();
        skuSalesList.forEach(skuSales -> {
            map.put(skuSales.getProdSkuId(), skuSales.getSalesNumber());
        });

        return map;
    }

    private JSONObject getSkuSalesJson(String httpUrl, String cookie, String mallId, SkuSalesReq req) {
        StringBuilder content = new StringBuilder();
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Origin", "https://seller.kuajingmaihuo.com");
            conn.setRequestProperty("cookie", cookie);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("MallId", mallId);
            conn.setDoOutput(true);

            String warehouseReqJson = JSON.toJSONString(req);

            try (OutputStream os = conn.getOutputStream()) {
                os.write(warehouseReqJson.getBytes());
            }

            conn.connect();

            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = br.readLine()) != null) {
                content.append(inputLine);
            }
            br.close();
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSONObject.parseObject(content.toString());
    }

    @PostMapping("/queryWarehouse")
    public ResultVO<List<Warehouse>> queryWarehouse(@RequestHeader("access_token") String token, @RequestParam(value = "mallId") String mallId, @RequestParam(value = "productSkuId", required = false) String productSkuId, @RequestParam(value = "skuExtCode", required = false) String skuExtCode, @RequestParam(value = "productName", required = false) String productName) {
        List<Warehouse> warehouseList = new ArrayList<>();
        try {
            String cookie = "";
            if (token != null && !"".equals(token.trim())) {
                cookie = userInfoService.queryUserCookie(token);
                if ("".equals(cookie.trim())) {
                    return ResultVOUtil.error(1, "token不正确,请先登录Temu后台");
                }
            }

            List<Long> productSkuIds = warehouseService.queryProductSkuIds(mallId);
            if (productSkuIds == null || productSkuIds.size() < 1) {
                return ResultVOUtil.success(warehouseList);
            }
            //获取昨天日期
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String yesterday = format.format(cal.getTime());
            SkuSalesReq skuSalesReq = new SkuSalesReq();
            skuSalesReq.setStartDate(yesterday);
            skuSalesReq.setEndDate(yesterday);
            skuSalesReq.setProductSkuIds(productSkuIds);
            Map<Long, Integer> skuSalesMap = querySkuSalesNumber(cookie, skuSalesReq, mallId);

            //查询
            warehouseList = warehouseService.queryWarehouse(mallId, productName, skuExtCode, productSkuId);
            if (warehouseList != null && warehouseList.size() > 0) {
                setWarehouseList(warehouseList, skuSalesMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVOUtil.error(1, e.getMessage());
        }
        return ResultVOUtil.success(warehouseList);
    }


    public void updateWarehouse(List<subOrder> subOrderList) {
        try {
            subOrderList.forEach(subOrder -> {
                String productName = subOrder.getProductName();
                String mallId = subOrder.getSupplierId();
                String productSkcPicture = subOrder.getProductSkcPicture();
                List<SkuQuantityDetail> skuQuantityDetailList = subOrder.getSkuQuantityDetailList();
                if (skuQuantityDetailList != null && skuQuantityDetailList.size() > 0) {
                    skuQuantityDetailList.forEach(skuQuantityDetail -> {
                        String skuExtCode = skuQuantityDetail.getSkuExtCode();
                        String className = skuQuantityDetail.getClassName();
                        String currencyType = skuQuantityDetail.getCurrencyType();
                        Double supplierPrice = skuQuantityDetail.getSupplierPrice();
                        String productSkuId = skuQuantityDetail.getProductSkuId();
                        String productSkcId = skuQuantityDetail.getProductSkcId();

                        Integer todaySaleVolume = skuQuantityDetail.getTodaySaleVolume() == null ? 0 : skuQuantityDetail.getTodaySaleVolume();
                        Integer lastSevenDaysSaleVolume = skuQuantityDetail.getLastSevenDaysSaleVolume() == null ? 0 : skuQuantityDetail.getLastSevenDaysSaleVolume();
                        Integer lastThirtyDaysSaleVolume = skuQuantityDetail.getLastThirtyDaysSaleVolume() == null ? 0 : skuQuantityDetail.getLastThirtyDaysSaleVolume();

                        Integer warehouseInventoryNum = skuQuantityDetail.getInventoryNumInfo().getWarehouseInventoryNum() == null ? 0 : skuQuantityDetail.getInventoryNumInfo().getWarehouseInventoryNum();
                        Integer waitReceiveNum = skuQuantityDetail.getInventoryNumInfo().getWaitReceiveNum() == null ? 0 : skuQuantityDetail.getInventoryNumInfo().getWaitReceiveNum();
                        Integer unavailableWarehouseInventoryNum = skuQuantityDetail.getInventoryNumInfo().getUnavailableWarehouseInventoryNum() == null ? 0 : skuQuantityDetail.getInventoryNumInfo().getUnavailableWarehouseInventoryNum();

                        Warehouse warehouse = new Warehouse();
                        warehouse.setMallId(mallId);
                        warehouse.setProductName(productName);
                        warehouse.setProductSkcPicture(productSkcPicture);

                        warehouse.setSkuExtCode(skuExtCode);
                        warehouse.setClassName(className);
                        warehouse.setCurrencyType(currencyType);
                        warehouse.setTodaySaleVolume(todaySaleVolume);
                        warehouse.setLastSevenDaysSaleVolume(lastSevenDaysSaleVolume);
                        warehouse.setLastThirtyDaysSaleVolume(lastThirtyDaysSaleVolume);
                        warehouse.setBuyingPrice(0.00);

                        if (supplierPrice != null) {
//                        BigDecimal bd = BigDecimal.valueOf(supplierPrice/100.00).setScale(2, RoundingMode.HALF_UP);

                            warehouse.setSupplierPrice(supplierPrice / 100.00);
                        } else {
                            warehouse.setSupplierPrice(0.00);
                        }

                        warehouse.setBuyingPrice(0.00);
                        warehouse.setProductSkuId(productSkuId);
                        warehouse.setProductSkcId(productSkcId);

                        warehouse.setWarehouseInventoryNum(Integer.valueOf(warehouseInventoryNum));
                        warehouse.setWaitReceiveNum(Integer.valueOf(waitReceiveNum));
                        warehouse.setUnavailableWarehouseInventoryNum(unavailableWarehouseInventoryNum);
                        int i = warehouseService.checkSkuCodeExist(mallId, skuExtCode);
                        if (i > 0) {
                            warehouseService.updateWarehouse(warehouse);
                        } else {
                            warehouseService.saveWarehouse(warehouse);
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
